package com.lanyou.cook.service.security;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.lanyou.cook.entity.domain.userManagement.Permission;
import com.lanyou.cook.entity.domain.userManagement.Role;
import com.lanyou.cook.entity.domain.userManagement.User;
import com.lanyou.cook.repository.userManagement.PermissionRepository;

/**
 * 权限相关的业务逻辑层
 *
 */
@Service
public class PermissionService {

	@Autowired
	private PermissionRepository permissionRepository;
	
	/**
	 * 查询指定用户所拥有权限的集合
	 * @param userCode 类型:String 待查询用户的用户编码
	 * @return 类型:List 待查询用户所拥有权限的集合@
	 */
	public List<Permission> findPermissionsOfUser(String userCode){
		return permissionRepository.findAll(new Specification<Permission>() {
			
			@Override
			public Predicate toPredicate(Root<Permission> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Join<Permission, Role> joinRole = root.join("roles");
				Join<Role, User> joinUser = joinRole.join("user");
				
				List<Predicate> predicatesList = new ArrayList<>();
				predicatesList.add(cb.equal(joinUser.get("userCode"), userCode));
				
				query.where(predicatesList.toArray(new Predicate[predicatesList.size()]));
				return null;
			}
		});
	}
}
